﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PearTunes.Model;
using PearTunes.DAL;
using System.ServiceModel;
using System.IO;

namespace PearTunes.DBTEST
{
    class Program
    {
        static void Main(string[] args)
        {


            PearTunesServiceReference.PearTunesServiceClient proxy = new PearTunesServiceReference.PearTunesServiceClient();
            proxy.Open();

            var albums = proxy.GetAlbums();


            foreach (var item in albums)
            {
                Console.WriteLine(item.Title);
                foreach (var t in item.Tracks)
                {
                    Console.WriteLine("    " + t.Title);
                }
            }

            Track trackToGet = albums.Last().Tracks.First();
            
            try
            {
            var fs = proxy.GetFileStream(trackToGet.FilePath);

            string saveTo = @"C:\PearTunesMusicFromNet\" + trackToGet.Artist + "-" + trackToGet.Title + ".mp3";
            // create a write stream
            FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.Write);
            // write to the stream
            
                ReadWriteStream(fs, writeStream);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                
            }
            Console.WriteLine("A file sikeresen mentve");

            proxy.Close();
            Console.ReadKey();
        }

        private static void ReadWriteStream(Stream readStream, Stream writeStream)
        {
            int Length = 256;
            Byte[] buffer = new Byte[Length];
            int bytesRead = readStream.Read(buffer, 0, Length);
            // write the required bytes
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = readStream.Read(buffer, 0, Length);
            }
            readStream.Close();
            writeStream.Close();
        }


    }
}
